package com.suxin.spring.configuration;

import lombok.Data;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;

/**
 * @author Tang
 * @classname ConfigurationPropertiesBean
 * @description [  ]
 * @date 2023/3/18 17:34
 */
@Data
public class ConfigurationPropertiesBean {

    private final String name;

    private final Object instance;

    private final ConfigurationProperties annotation;

    private final Bindable<?> bindTarget;

    public ConfigurationPropertiesBean(Object bean, String beanName,
                                       ConfigurationProperties annotation, Bindable<?> bindable) {
        this.name = beanName;
        this.instance = bean;
        this.annotation = annotation;
        this.bindTarget = bindable;
    }

    public static ConfigurationPropertiesBean get(ApplicationContext applicationContext, Object bean, String beanName) {
        final MergedAnnotation<ConfigurationProperties> annotation = MergedAnnotations.from(bean).get(ConfigurationProperties.class);
        final ConfigurationProperties configurationProperties = annotation.synthesize();
        final Bindable<?> bindable = Bindable.of(bean.getClass()).withAnnotations(configurationProperties);
        return createBean(bean,beanName,configurationProperties,bindable);
    }

    private static ConfigurationPropertiesBean createBean(Object bean, String beanName,ConfigurationProperties configurationProperties, Bindable<?> bindable) {
        return new ConfigurationPropertiesBean(bean,beanName,configurationProperties,bindable);
    }
}
